package com.luyuan.crm.product.service.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.Order;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.luyuan.crm.product.model.Product;
import com.luyuan.crm.product.model.ProductType;
import com.luyuan.crm.product.service.ProductService;
import com.ruijie.foundation.dao.extend.support.HibernateEntityExtendDao;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaQueryTemplate;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;

@SuppressWarnings("unchecked")
public class ProductServiceImpl extends HibernateEntityExtendDao<Product> implements ProductService {

    @Override
    public Page pagedQuery(CriteriaTemplate criteria, int pageNo, int pageSize, List<Order> orders) {
        CriteriaQueryTemplate qt = new CriteriaQueryTemplate(getSessionFactory());
        return qt.pagedQuery(criteria, pageNo, pageSize, orders);
    }

    @Override
    public Product getProductById(Serializable id) {
        return this.get(id);
    }

    @Override
    public List<Product> findByProductType(ProductType productType) {
        return find("from Product where productType = ? and enabled = true", productType);
    }

    @Override
    public void updateProduct(Product product) {
        this.update(product);
    }

    @Override
    public void addProduct(Product product) {
        this.save(product);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void deleteProductById(Serializable id) {
        this.remove(id);
    }

    @Override
    public void batchDeleteProduct(Serializable[] ids) {
        this.remove(ids);
    }

    @Override
    public boolean hasChildProducts(Serializable id) {
        Long count = (Long) findUniqueBy("select count(*) from Product t where t.productType.id = ?",
                new Object[] { id });
        return count > 0;
    }

    @Override
    public void disableByProductId(Serializable id) {
        update("update Product set enabled = false where id = ?", id);
        clear();
    }

    @Override
    public void enableByProductId(Serializable id) {
        update("update Product set enabled = true where id = ?", id);
        clear();
    }
}
